#include "consumptionservice.h"
#include <QDebug>
#include <QDateTime>
#include <algorithm>

ConsumptionService::ConsumptionService(Database *db)
    : m_db(db)
{
    m_consumptionDAO = new ConsumptionDAO(db);
}

ConsumptionService::~ConsumptionService()
{
    delete m_consumptionDAO;
}

QVector<QMap<QString, QVariant>> ConsumptionService::getFormattedConsumptionByMember(int memberId)
{
    if (!isValidMemberId(memberId)) {
        qDebug() << "无效的会员ID:" << memberId;
        return QVector<QMap<QString, QVariant>>();
    }

    auto records = m_consumptionDAO->getConsumptionByMemberId(memberId);
    
    // 增强每条记录的显示信息
    for (auto &record : records) {
        enhanceConsumptionRecord(record);
    }
    
    return records;
}

QVector<QMap<QString, QVariant>> ConsumptionService::getFormattedConsumptionByLevel(int levelId)
{
    if (!isValidLevelId(levelId)) {
        qDebug() << "无效的等级ID:" << levelId;
        return QVector<QMap<QString, QVariant>>();
    }

    auto records = m_consumptionDAO->getConsumptionByMemberLevel(levelId);
    
    // 增强每条记录的显示信息
    for (auto &record : records) {
        enhanceConsumptionRecord(record);
    }
    
    return records;
}

QVector<QMap<QString, QVariant>> ConsumptionService::getAllConsumptionForDisplay()
{
    auto records = m_consumptionDAO->getAllConsumptionRecords();
    
    // 增强每条记录的显示信息
    for (auto &record : records) {
        enhanceConsumptionRecord(record);
    }
    
    return records;
}

QVector<QMap<QString, QVariant>> ConsumptionService::getConsumptionByDateRange(const QDateTime &startDate, const QDateTime &endDate)
{
    if (startDate > endDate) {
        qDebug() << "开始时间不能晚于结束时间";
        return QVector<QMap<QString, QVariant>>();
    }

    auto records = m_consumptionDAO->getConsumptionByDateRange(startDate, endDate);
    
    // 增强每条记录的显示信息
    for (auto &record : records) {
        enhanceConsumptionRecord(record);
    }
    
    return records;
}

QMap<QString, QVariant> ConsumptionService::getMemberConsumptionSummary(int memberId)
{
    if (!isValidMemberId(memberId)) {
        qDebug() << "无效的会员ID:" << memberId;
        return QMap<QString, QVariant>();
    }

    auto stats = m_consumptionDAO->getMemberConsumptionStats(memberId);
    
    // 格式化统计信息
    QMap<QString, QVariant> summary;
    summary["order_count"] = stats.value("order_count", 0);
    summary["total_consumption"] = formatAmount(stats.value("total_consumption", 0.0).toDouble());
    summary["total_discount"] = formatAmount(stats.value("total_discount", 0.0).toDouble());
    summary["total_payment"] = formatAmount(stats.value("total_payment", 0.0).toDouble());
    summary["avg_order_amount"] = formatAmount(stats.value("avg_order_amount", 0.0).toDouble());
    summary["last_order_time"] = formatDateTime(stats.value("last_order_time"));
    
    // 计算节省信息
    double totalConsumption = stats.value("total_consumption", 0.0).toDouble();
    double totalDiscount = stats.value("total_discount", 0.0).toDouble();
    summary["savings_info"] = calculateSavingsText(totalConsumption, totalDiscount);
    
    return summary;
}

QVector<QMap<QString, QVariant>> ConsumptionService::getLevelConsumptionStats()
{
    auto stats = m_consumptionDAO->getConsumptionStatsByLevel();
    
    // 格式化统计信息
    for (auto &record : stats) {
        record["formatted_total_consumption"] = formatAmount(record.value("total_consumption", 0.0).toDouble());
        record["formatted_total_discount"] = formatAmount(record.value("total_discount", 0.0).toDouble());
        record["formatted_total_payment"] = formatAmount(record.value("total_payment", 0.0).toDouble());
        record["formatted_avg_order_amount"] = formatAmount(record.value("avg_order_amount", 0.0).toDouble());
        
        // 计算平均折扣率
        double totalConsumption = record.value("total_consumption", 0.0).toDouble();
        double totalDiscount = record.value("total_discount", 0.0).toDouble();
        if (totalConsumption > 0) {
            double avgDiscountRate = (totalDiscount / totalConsumption) * 100;
            record["avg_discount_rate"] = QString::number(avgDiscountRate, 'f', 1) + "%";
        } else {
            record["avg_discount_rate"] = "0.0%";
        }
    }
    
    return stats;
}

QVector<QMap<QString, QVariant>> ConsumptionService::getOrderDetails(int orderId)
{
    if (!isValidOrderId(orderId)) {
        qDebug() << "无效的订单ID:" << orderId;
        return QVector<QMap<QString, QVariant>>();
    }

    auto details = m_consumptionDAO->getConsumptionDetails(orderId);
    
    // 格式化订单详情
    for (auto &detail : details) {
        detail["formatted_unit_price"] = formatAmount(detail.value("unit_price", 0.0).toDouble());
        detail["formatted_subtotal"] = formatAmount(detail.value("subtotal", 0.0).toDouble());
        detail["discount_status"] = detail.value("is_discounted", 0).toInt() == 1 ? "已折扣" : "原价";
    }
    
    return details;
}

QVector<QMap<QString, QVariant>> ConsumptionService::filterConsumptionByAmount(const QVector<QMap<QString, QVariant>> &records, double minAmount, double maxAmount)
{
    QVector<QMap<QString, QVariant>> filtered;
    
    for (const auto &record : records) {
        double amount = record.value("final_amount", 0.0).toDouble();
        if (amount >= minAmount && amount <= maxAmount) {
            filtered.append(record);
        }
    }
    
    return filtered;
}

QVector<QMap<QString, QVariant>> ConsumptionService::filterConsumptionByMember(const QVector<QMap<QString, QVariant>> &records, int memberId)
{
    QVector<QMap<QString, QVariant>> filtered;
    
    for (const auto &record : records) {
        if (record.value("member_id", 0).toInt() == memberId) {
            filtered.append(record);
        }
    }
    
    return filtered;
}

QVector<QMap<QString, QVariant>> ConsumptionService::filterConsumptionByLevel(const QVector<QMap<QString, QVariant>> &records, int levelId)
{
    QVector<QMap<QString, QVariant>> filtered;
    
    for (const auto &record : records) {
        if (record.value("level_id", -1).toInt() == levelId) {
            filtered.append(record);
        }
    }
    
    return filtered;
}

QVector<QMap<QString, QVariant>> ConsumptionService::filterConsumptionByStatus(const QVector<QMap<QString, QVariant>> &records, int status)
{
    QVector<QMap<QString, QVariant>> filtered;
    
    for (const auto &record : records) {
        if (record.value("order_status", -1).toInt() == status) {
            filtered.append(record);
        }
    }
    
    return filtered;
}

QVector<QMap<QString, QVariant>> ConsumptionService::filterConsumptionByPaymentMethod(const QVector<QMap<QString, QVariant>> &records, const QString &methodName)
{
    QVector<QMap<QString, QVariant>> filtered;
    
    for (const auto &record : records) {
        if (record.value("method_name", "").toString() == methodName) {
            filtered.append(record);
        }
    }
    
    return filtered;
}

QVector<QMap<QString, QVariant>> ConsumptionService::sortConsumptionByTime(const QVector<QMap<QString, QVariant>> &records, bool ascending)
{
    QVector<QMap<QString, QVariant>> sorted = records;
    
    std::sort(sorted.begin(), sorted.end(), [ascending](const QMap<QString, QVariant> &a, const QMap<QString, QVariant> &b) {
        QDateTime timeA = a.value("order_time").toDateTime();
        QDateTime timeB = b.value("order_time").toDateTime();
        return ascending ? timeA < timeB : timeA > timeB;
    });
    
    return sorted;
}

QVector<QMap<QString, QVariant>> ConsumptionService::sortConsumptionByAmount(const QVector<QMap<QString, QVariant>> &records, bool ascending)
{
    QVector<QMap<QString, QVariant>> sorted = records;
    
    std::sort(sorted.begin(), sorted.end(), [ascending](const QMap<QString, QVariant> &a, const QMap<QString, QVariant> &b) {
        double amountA = a.value("final_amount").toDouble();
        double amountB = b.value("final_amount").toDouble();
        return ascending ? amountA < amountB : amountA > amountB;
    });
    
    return sorted;
}

QString ConsumptionService::formatAmount(double amount)
{
    return QString("¥%1").arg(QString::number(amount, 'f', 2));
}

QString ConsumptionService::formatDateTime(const QVariant &dateTime)
{
    if (dateTime.isNull() || !dateTime.isValid()) {
        return "--";
    }
    
    QDateTime dt = dateTime.toDateTime();
    if (!dt.isValid()) {
        return "--";
    }
    
    return dt.toString("yyyy-MM-dd hh:mm:ss");
}

QString ConsumptionService::formatOrderStatus(int status)
{
    switch (status) {
        case 0: return "待支付";
        case 1: return "已支付";
        case 2: return "已完成";
        case 3: return "已取消";
        case 4: return "已退款";
        default: return "未知状态";
    }
}

QString ConsumptionService::formatPaymentMethod(const QString &methodName)
{
    if (methodName.isEmpty()) {
        return "未知";
    }
    return methodName;
}

QString ConsumptionService::formatDiscountInfo(double totalAmount, double discountAmount)
{
    if (totalAmount <= 0) {
        return "无折扣";
    }
    
    if (discountAmount <= 0) {
        return "无折扣";
    }
    
    double discountRate = (discountAmount / totalAmount) * 100;
    return QString("节省 %1 (%2%)").arg(formatAmount(discountAmount), QString::number(discountRate, 'f', 1));
}

bool ConsumptionService::isValidMemberId(int memberId)
{
    return memberId > 0;
}

bool ConsumptionService::isValidOrderId(int orderId)
{
    return orderId > 0;
}

bool ConsumptionService::isValidLevelId(int levelId)
{
    return levelId >= 0 && levelId <= 3; // 0=非会员, 1=初级, 2=中级, 3=高级
}

void ConsumptionService::enhanceConsumptionRecord(QMap<QString, QVariant> &record)
{
    // 格式化金额
    record["formatted_total_amount"] = formatAmount(record.value("total_amount", 0.0).toDouble());
    record["formatted_discount_amount"] = formatAmount(record.value("discount_amount", 0.0).toDouble());
    record["formatted_final_amount"] = formatAmount(record.value("final_amount", 0.0).toDouble());
    
    // 格式化时间
    record["formatted_order_time"] = formatDateTime(record.value("order_time"));
    
    // 格式化状态
    record["formatted_status"] = formatOrderStatus(record.value("order_status", 0).toInt());
    
    // 格式化支付方式
    record["formatted_payment_method"] = formatPaymentMethod(record.value("method_name", "").toString());
    
    // 计算并格式化折扣信息
    double totalAmount = record.value("total_amount", 0.0).toDouble();
    double discountAmount = record.value("discount_amount", 0.0).toDouble();
    record["discount_info"] = formatDiscountInfo(totalAmount, discountAmount);
    
    // 添加状态颜色代码（用于UI显示）
    record["status_color"] = getStatusColorCode(record.value("order_status", 0).toInt());
    
    // 添加等级显示名称
    record["level_display_name"] = record.value("level_name", "非会员").toString();
}

QString ConsumptionService::calculateSavingsText(double totalAmount, double discountAmount)
{
    if (totalAmount <= 0 || discountAmount <= 0) {
        return "暂无优惠";
    }
    
    double savingsRate = (discountAmount / totalAmount) * 100;
    return QString("累计节省 %1，平均优惠 %2%")
           .arg(formatAmount(discountAmount))
           .arg(QString::number(savingsRate, 'f', 1));
}

QString ConsumptionService::getStatusColorCode(int status)
{
    switch (status) {
        case 0: return "#FF9800"; // 橙色 - 待支付
        case 1: return "#4CAF50"; // 绿色 - 已支付
        case 2: return "#2196F3"; // 蓝色 - 已完成
        case 3: return "#9E9E9E"; // 灰色 - 已取消
        case 4: return "#F44336"; // 红色 - 已退款
        default: return "#000000"; // 黑色 - 未知
    }
}

QString ConsumptionService::getLevelDisplayName(int levelId)
{
    switch (levelId) {
        case 0: return "非会员";
        case 1: return "初级会员";
        case 2: return "中级会员";
        case 3: return "高级会员";
        default: return "未知等级";
    }
}